package com.kits.other

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

/**
 * 遗留权限问题
 */
class ShareActivity : AppCompatActivity(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_share)

        intent?.takeIf {
            Intent.ACTION_SEND == it.action &&  it.type != null
        }?.let {
            when(it.type){
                "text/plain"->{
                    println("处理分享文件")
                    handleText(it)
                }
                else->{
                    println("其他文件分享")
                }
            }
        }
    }


    private fun handleText(intent: Intent){
        val shareUri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
        shareUri?.let {
            // 如何查看权限呢？
            val bundle=intent.extras
            bundle?.keySet()?.forEach{
                println("key == $it;value == ${bundle.get(it)}")
            }
            println("flags == ${intent.flags}")
            read(shareUri)
            write(shareUri)
//            when(intent.flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)){
//                Intent.FLAG_GRANT_READ_URI_PERMISSION->{
//                    println("获取到读权限")
//                }
//                Intent.FLAG_GRANT_WRITE_URI_PERMISSION->{
//                    println("获取到写权限")
//                }
//                Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION->{
//                    println("获取到读写权限")
//                }
//            }
        }
    }

    private fun read(uri:Uri){
        val inputStream  = contentResolver.openInputStream(uri)
        inputStream?.let {
            val buf = ByteArray(it.available())
            it.read(buf)
            println("buf == ${String(buf)}")
            it.close()
        }

    }

    private fun write(uri:Uri){
        val outputSystem = contentResolver.openOutputStream(uri)
        outputSystem?.let {
            it.write("在另一个APP写入的问题\n".toByteArray())
            it.close()
        }
    }



}